package com.hunter.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * 2010-11-9 下午10:23:23<br>
 * 处理搜索历史的工具类
 * 
 * @author mkk
 */
public class HistoryUtil {

	/**
	 * 存放历史数据文件
	 */
	public static final String HISTORY_FILE = "history";

	private static HistoryUtil util = new HistoryUtil();
	// Save keywords
	private List<String> keyWords = new ArrayList<String>();
	// Save current key word index
	private int index = 0;

	/**
	 * Private constructor
	 */
	private HistoryUtil() {
		// load properties keywords
		loadKeywords();
		//Init index
		if (!keyWords.isEmpty()) {
			index = keyWords.size() - 1;
		}
	}

	/**
	 * Get unique instance
	 * 
	 * @return HistoryUtil
	 */
	public static HistoryUtil getHistoryUtil() {
		return util;
	}

	/**
	 * Save search keyword.<br>
	 * when click search button,call this method
	 * 
	 * @param keyWord
	 *            Search key word
	 */
	public void saveKeyword(String keyWord) {
		if (SystemUtil.hasText(keyWord)) {
			keyWords.add(keyWord);
			index = keyWords.size() - 1;
		}
	}

	/**
	 * Get next keyword<br>
	 * If no next keyword,return empty string
	 * 
	 * @return Next key word
	 */
	public String getNextKeyword() {
		if (index < keyWords.size() - 1) {
			return keyWords.get(++index);
		}
		return "";
	}

	/**
	 * Get previous key word<br>
	 * If no previous key word,return empty string
	 * 
	 * @return Previous key word
	 */
	public String getPreviousKeyword() {
		if (index >= 0 && index < keyWords.size()) {
			return keyWords.get(index--);
		}
		return "";
	}

	/**
	 * Load keywords from disk
	 */
	private void loadKeywords() {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(getFile()));
			String s;
			while ((s = br.readLine()) != null) {
				if (SystemUtil.hasText(s)) {
					keyWords.add(s);
				}
			}
		} catch (IOException e) {
			LogUtil.saveExceptionLog(e);
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
				}
			}
		}
	}

	/**
	 * Save RAM keywords to disk,<br>
	 * when exist system call this
	 */
	public void persistenceKeywods() {
		if (keyWords.isEmpty()) {
			return;
		}
		PrintWriter pw = null;
		try {
			pw = new PrintWriter(getFile());
			for (String words : keyWords) {
				pw.println(words);
			}
			pw.flush();
		} catch (IOException e) {
			LogUtil.saveExceptionLog(e);
		} finally {
			if (pw != null) {
				pw.close();
			}
		}
	}

	/**
	 * Get save key words file,if file not exist,create new file
	 * 
	 * @return File
	 * @throws IOException
	 *             IOException
	 */
	private File getFile() throws IOException {
		File file = new File(HISTORY_FILE);
		if (!file.exists()) {
			file.createNewFile();
		}
		return file;
	}

}
